<template>
	<div class="app-container group-bg" v-loading="loading">
		<div class="group">
			<el-form ref="form" :model="form" :rules="rules" label-width="120px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="分组名称" prop="groupName">
							<el-input v-model="form.groupName" placeholder="请输入分组名称" style="width:80%" />
							</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="分组负责人" prop="userId">
							<el-select v-model="form.userId" placeholder="请选择分组负责人" filterable :filter-method="filterGrouper">
								<el-option v-for="item of leaderList" :key="item.userId" :value="item.userId" :label="item.userName"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="分组描述" prop="description">
							<el-input type="textarea" v-model="form.description" placeholder="请输入分组描述" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<div class="tree-title">分组权限</div>
						<div class="search">
							<el-form-item label="分层名称" prop="layer">
								<el-input v-model.trim="authKeyword" style="width:270px;" placeholder="请输入分层名称关键字" />
								<el-button type="primary" style="float:right;margin-left:16px;" @click="handleAuth">查询</el-button>
								<el-button icon="el-icon-s-operation" style="float:right;" @click="authReset"></el-button>
							</el-form-item>
						</div>
						<div class="custom-tree" style="overflow:hidden;">
							<!--  -->
							<div class="custom-tree-header">
								<span class="tree-th t1">数据库表单目录</span>
								<span class="tree-th" style="width:220px;">权限选择</span>
							</div>
							<el-tree :filter-node-method="filterNode" :data="databaseTree" show-checkbox node-key="id" ref="authTree" :props="{label:'dirName'}" :default-checked-keys="defaultTreeList" :check-strictly="strictly" class="g-tree">
							</el-tree>
						</div>

					</el-col>

					<el-col :span="24" v-if="isEdit">
						<member-list :isEdit="true" ref="memberList"></member-list>
					</el-col>
				</el-row>
			</el-form>
			<div style="text-align:center;margin-top:20px;">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</div>

	</div>
</template>

<script>

	import { addGroup, updateGroup, getGroup } from "@/api/dataManagement/system/group";
	import { groupTree } from "@/api/dataManagement/system/dir";
	import { listUser } from "@/api/dataManagement/system/user";
	import memberList from './modules/memberList'

	export default {
		components: { memberList },
		data() {
			return {
				loading: false,
				// 是否编辑
				isEdit: false,
				// 表单参数
				form: {},
				// 表单校验
				rules: {
					groupName: [
						{ required: true, message: "分组名不能为空", trigger: "blur" }
					],
					userId: [
						{ required: true, message: "分组负责人必选", trigger: "blur" }
					],
				},
				//   权限数据
				databaseTree: [],
				queryAuthData: [],
				// 负责人列表
				leaderList: [],
				authKeyword: '',
				// 数据原来的列表
				defaultTreeList: [],
				// 父子不关联
				strictly:true
			}
		},
		created() {
			this.getGroupItem()
			this.getDatabaseTree()
			this.getLeaderList()
		},
		methods: {
			// 分组详情
			getGroupItem() {
				console.log("分组ID:", this.$route.query.id)
				if (this.$route.name == "EditGroup" && this.$route.query.id) {
					this.isEdit = true
					this.loading = true
					getGroup(this.$route.query.id).then(res => {
						console.log("res:", res)
						this.form = res.data
						this.defaultTreeList = res.data.dataDirIds
						this.strictly = false
						this.$refs.memberList.getGroupId(res.data)
						this.loading = false
					}).catch(err => {
						this.loading = false
					})
				}
			},
			// 获取数据库表单目录
			getDatabaseTree() {
				groupTree().then(res => {
					if (res.code == 200) {
						this.databaseTree = res.data.children
					}
				})
			},
			// 获取负责人列表
			getLeaderList(value) {
				listUser({ userName: value }).then(res => {
					if (res.code == 200) {
						// console.log("res:",res)
						this.leaderList = res.rows
					}
				})
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					// let params = {...this.form,dataDirIds:this.$refs.authTree.getCheckedKeys()}
					if (valid) {
						let params = { ...this.form, dataDirIds: this.$refs.authTree.getHalfCheckedKeys().concat(this.$refs.authTree.getCheckedKeys()) }
						console.log("提交参数：", params)
						// 新增
						this.loading = true
						if (!this.isEdit) {
							addGroup(params).then(res => {
								if (res.code == 200) {
									this.msgSuccess(res.msg)
									this.deleteTagsView()
									this.$router.push({ path: '/manager/group/list' })
								} else {
									this.msgError(res.msg)
								}
								this.loading = false
							}).catch(err => {
								this.msgError(err)
								this.loading = false
							})
						}
						// 修改
						else {
							updateGroup(params).then(res => {
								if (res.code == 200) {
									this.msgSuccess(res.msg)
									this.deleteTagsView()
									this.$router.push({ path: '/manager/group/list' })
								} else {
									this.msgError(res.msg)
								}
								this.loading = false
							}).catch(err => {
								this.msgError(err)
								this.loading = false
							})
						}

					}
				});
			},
			// 取消按钮
			cancel() {
				this.deleteTagsView()
				this.$router.push({ path: '/manager/group/list' })
			},
			deleteTagsView() {
				let view = { ...this.$route }
				this.$store.dispatch('tagsView/delView', view).then(() => { })
			},
			// 权限列表查询
			handleAuth() {
				this.$refs.authTree.filter(this.authKeyword)
			},
			// 展示全部
			authReset() {
				this.$refs.authTree.filter('')
			},
			filterNode(value, data, node) {
				return this.checkBelongToChooseNode(value, data, node);
			},
			// 判断传入的节点是不是选中节点的子节点
			checkBelongToChooseNode(value, data, node) {
				let label = "dirName"
				if (data[label].indexOf(value) !== -1) {
					return true;
				}
				const level = node.level;
				// 如果传入的节点本身就是一级节点就不用校验了
				if (level === 1) {
					return false;
				}
				// 先取当前节点的父节点
				let parentData = node.parent;
				// 遍历当前节点的父节点
				let index = 0;
				while (index < level - 1) {
					// 如果匹配到直接返回
					if (parentData.data[label].indexOf(value) != -1) {
						return true;
					}
					// 否则的话再往上一层做匹配
					parentData = parentData.parent;
					index++;
				}
				// 没匹配到返回false
				return false;
			},
			// 分组负责人筛选
			filterGrouper(val) {
				this.getLeaderList(val)
			}

		}
	}
</script>

<style lang="scss" scoped>
	@import "~@/assets/styles/system/tree.scss";
	.group-bg {
		background: #ffffff;
		padding: 16px;
		margin: 0px 20px 20px;
	}
	.group {
		// width: 870px;
		margin: 10px 20px 0;
	}
	.g-tree {
		::v-deep.el-tree-node__content {
			display: block;
			position: relative;
			margin-left: 10px;
			width: 100%;
			.el-checkbox {
				position: absolute;
				right: 180px;
			}
		}
		::v-deep.el-tree-node__children {
			margin-left: 18px;
			width: 100%;
		}
	}
	::v-deep.el-form-item {
		padding-right: 10px;
	}
</style>